﻿using System;
using System.Diagnostics;
using System.Threading.Tasks;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Iai.V20200303;
using TencentCloud.Iai.V20200303.Models;
using System.Drawing;
using project1113.Wrold;
using ViewFaceCore;
using ViewFaceCore.Core;
using project1113.Wrold;
using project1113;
using project1113.SomeTools;
using System.Windows.Forms;
using project1113.iniParser;
using project1113.observer;

namespace FaceRecognizer
{
    /// <summary>
    /// 人脸检测模块
    /// </summary>
    public class Face
    {
        private Group group = new Group("robot", "2023");

        private readonly IaiClient client;
        private readonly FaceDetector faceDetector = new FaceDetector();
        public bool HaveFace { get; set; } = false;
        public string? FaceName { get; private set; }
        private string? _faceid { get; set; } = null;
        public bool Running { get; set; } = true;
        public Face()
        {
            client = Init();
            Task.Run( () =>
            {
 
                while (true)
                {
                    if (Running)
                    {
                        try
                        {
                            Bitmap? bitmap = null;
                            lock (WorldModel.CurrentWorld.lockObject)
                            {
                                if (WorldModel.CurrentWorld.Camera.OutputBitmap != null)
                                {
                                    bitmap = WorldModel.CurrentWorld.Camera.OutputBitmap.Clone() as Bitmap;
                                }
                            }
                            if (bitmap != null)
                            {
                                HaveFace = LocalFacialRec(bitmap);
                                if (HaveFace)
                                {
                                    FaceName = OutPutName(bitmap);
                                    bitmap.Dispose();
                                    HaveFace = false;
                                }
                                if (bitmap != null)
                                    bitmap.Dispose();
                            }
                        }
                        catch (Exception e)
                        {
                            HaveFace = false;
                        }

                    }

                }
            });
        }

        private bool LocalFacialRec(Bitmap ? bitmap)
        {

                var infos = faceDetector.Detect(bitmap.ToFaceImage());
                if(infos.Length>0) 
                {
                    HaveFace = true;
                }
                else
                {
                    HaveFace = false;
                }
                return HaveFace;
            
        }
        public async Task<bool> Compare(string name, Bitmap bitmap)
        {
            if (name == GoalName(bitmap))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public string OutPutName(Bitmap ? bitmap)
        {
            string name = GoalName(bitmap);
            if (name != null)
                //return PersonTable.dictionary[name];
                return WorldModel.CurrentWorld.SettingTable.GetPerson(name).PersonName;
            else
                return name;
        }

        private string GoalName(Bitmap bitmap)
        {


            return SearchPerson(client, group, FileManager.BitmapToBase64(bitmap));
        }

        public void PersonAdd(Bitmap bitmap, string personid,string name)
        {
            IaiClient client = Init();

            //Add(client,new Person("2023",personid,name,FileManager.BitmapToBase64(bitmap)),new Group("facetest", "2023"));
        }

        public IaiClient Init()
        {
           
            string iniFilePath = @"conf\Faceconf.ini";
            var iniParser = new IniParser(iniFilePath, new Observe_err());
            string? _SecretId = null;
            string? _SecretKey = null;
            string? _region = null;

            try
            {
                _SecretId = iniParser.GetSetting("_SecretId") ?? throw new Exception("缺少参数: _SecretId");
                _SecretKey = iniParser.GetSetting("_SecretKey") ?? throw new Exception("缺少参数: _SecretKey");
                _region = iniParser.GetSetting("region") ?? throw new Exception("缺少参数: region");
            }
            catch (Exception e)
            {
                //应该做一下观察器，我就算了,懒得麻烦--zlj
                MessageBox.Show(e.Message);
                StaticLogWrite.Logger.Log(LogLevel.Error, e.Message);
            }

            Credential cred = new Credential
            {
                SecretId = _SecretId,
                SecretKey = _SecretKey
            //SecretId = "AKIDUwaIC1jHj15uVt34teHg3E8uTr5EF8tU",
            //SecretKey = "e2GPV1VwC6tUt3y64pXIuOWeiaEj06Rx"
        };

            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();

            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();

            httpProfile.Endpoint = ("iai.tencentcloudapi.com");

            clientProfile.HttpProfile = httpProfile;

            // 实例化要请求产品的client对象,clientProfile是可选的

            //region = "ap-chongqing"

            IaiClient client = new IaiClient(cred, _region, clientProfile);

            return client;
        }

        //人脸库的添加
        private void Add(IaiClient client, Person person, Group group) 
        {
            try
            {
                Debug.WriteLine("等待录入中......");

                person.Create(client, person.Name, group.Id, person.Id, person.Image);

                Debug.WriteLine("录入成功！！！");
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }

        //人脸查找
        private string SearchPerson(IaiClient client, Group group, string image)
        {
            _faceid = null;

            try
            { 


                SearchPersonsResponse rep = group.SearchPersons(image, client, new string[] { group.Id });
                
                foreach (var result in rep.Results)
                {
                    foreach (var candidate in result.Candidates)
                    {
                        if(candidate.Score>90)
                        {
                            _faceid = candidate.PersonId;


                            return _faceid;
                        }
                    }
                }

                return _faceid;
            }
            catch (Exception e)
            {
                //Debug.WriteLine(e.ToString());
                StaticLogWrite.Logger.Log(LogLevel.Error, e.Message);
                return _faceid;
            }
        }
    }
}
